package com.zp.base.admin.controller;

import com.zp.base.admin.common.constant.BizCodeEnum;
import com.zp.base.admin.common.utils.R;
import com.zp.base.admin.common.utils.StringAndDateUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.Resource;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.Date;

/**
 * 统一图片上传控制器
 *
 * @author ZhangPeng
 * @email zhangpeng98@aliyun.com
 * @create 2021-03-05 10:23
 */
@RestController
@RequestMapping("/upload")
@Slf4j
public class UploadController {

    @Value("${zp.upload.photo.suffix}")
    private String uploadPhotoSuffix;

    @Value("${zp.upload.photo.path}")
    private String uploadPhotoPath;

    @Value("${zp.upload.photo.maxSize}")
    private Long uploadPhotoMaxSize;

    @Value("${zp.upload.default.path}")
    private String uploadDefaultPath;

    @PostMapping("/upload_photo")
    @PreAuthorize("hasAuthority('upload:upload_photo')")
    public R upload(@RequestParam("photo") MultipartFile photo, Model model) {
        //判断上传文件的后缀是否正确
        String originalFilename = photo.getOriginalFilename();
        String substring = originalFilename.substring(originalFilename.lastIndexOf("."));
        if (!uploadPhotoSuffix.contains(substring)) {
            //图片格式错误
            return R.error(BizCodeEnum.UPLOAD_PHOTO_SUFFIX_ERROR.getCode(), BizCodeEnum.UPLOAD_PHOTO_SUFFIX_ERROR.getMsg());
        }

        //判断图片大小是否超过允许的最大大小
        if (photo.getSize() > uploadPhotoMaxSize * 1024) {
            return R.error(BizCodeEnum.UPLOAD_PHOTO_MAX_ERROR.getCode(), BizCodeEnum.UPLOAD_PHOTO_MAX_ERROR.getMsg());
        }

        //获取上传路径
        File file = new File(uploadPhotoPath);
        if (!file.exists()) {
            //不存在则创建
            file.mkdir();
        }
        //把图片按照日期分类
        String dateToString = StringAndDateUtil.dateToString(new Date(), "yyyyMMdd");
        File curFile= new File(uploadPhotoPath + "/" + dateToString);
        if (!curFile.exists()) {
            curFile.mkdir();
        }
        //重新给图片起名字  防止名称重复照成覆盖
        String fileName = System.currentTimeMillis() + substring;
        File uploadFile= new File(curFile, fileName);

        //上传
        try {
            photo.transferTo(uploadFile);
        } catch (IOException e) {
            log.error(e.getMessage());
        }
        return R.ok().put("data", uploadDefaultPath + dateToString + "/" + fileName);
    }
}
